package entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import net.sf.json.JSONObject;

import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

import exception.MultipleValidationErrors;

public class JsonRequest {
	private JSONObject r = new JSONObject();;
	private String[] fields;

	public JsonRequest(String request, String... expectedFields)
			throws MultipleValidationErrors {
		try {
			Map parsedRequest = (Map) JSONValue.parseWithException(request);
			r.putAll(parsedRequest);
		} catch (ParseException pe) {
			throw new MultipleValidationErrors("JSON request is malformed");
		}

		this.fields = expectedFields;

		validate();
	}

	private void validate() throws MultipleValidationErrors {
		ArrayList<String> errors = new ArrayList<String>();

		for (String eachField : fields) {
			Object value = r.get(eachField);
			if (value != null) {
				if (String.valueOf(value).isEmpty()) {
					errors.add(eachField + " is blank");
				} else {
					// no errors
				}
			} else {
				errors.add(eachField + " is missing");
			}
		}

		if (!errors.isEmpty()) {
			// sort errors in alphebatical order
			Collections.sort(errors);

			throw new MultipleValidationErrors(errors);
		}

	}

	public JSONObject getRequest() {
		return r;
	}

}
